package com.snail.common.mq.rabbitmq.handler;

import com.alibaba.fastjson2.JSON;
import com.snail.common.core.utils.StringUtils;
import com.snail.common.lock.Lock;
import com.snail.common.mq.constants.MqConstants;
import com.snail.common.mq.core.IMqProducerAndConsumerHandler;
import com.snail.common.mq.core.dto.MqDto;
import com.snail.common.mq.core.dto.MqResultDto;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description: Kafka消息生产和消费处理器
 * @Author: Snail
 * @CreateDate: 2023/11/21 14:27
 * @Version: V1.0
 */
@Service
public class RabbitMqProducerAndConsumerHandler implements IMqProducerAndConsumerHandler {

    @Autowired
    private Lock lock;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 发送MQ消息
     *
     * @param mqDto 消息体
     * @return 结果
     */
    @Override
    public <T> MqResultDto sendMq(MqDto<T> mqDto) {
        MqResultDto resultDto = new MqResultDto();
        String key = StringUtils.format(MqConstants.LOCK_KEY, mqDto.getTopic() + "_" + mqDto.getPriKey());
        try {
            //获取分布式锁
            if (lock.getLock(key)) {
                //发送MQ消息
                rabbitTemplate.convertAndSend(mqDto.getExchange(),mqDto.getRoutingKey(),JSON.toJSONString(mqDto));
                resultDto.setResult(Boolean.TRUE);
            }
        } catch (Exception e) {
            resultDto.setResult(Boolean.FALSE);
            resultDto.setErrorMsq(e.getMessage());
        }
        //释放分布式锁
        lock.unLock(key);
        return resultDto;
    }
}
